import { createRouter, createWebHistory } from 'vue-router'
import { menuListRoute } from '@/views/menuList/route'
import { appListRoute } from '@/views/appList/route'
import { roleRoute } from '@/views/role/route'
import { taskRoute } from '@/views/task/route'
import { polymerizationRoute } from '@/views/polymerization/route'
import { echartsMapRoute } from '@/views/echartsMap/route'
import { chinaMapRoute } from '@/views/chinaMap/route'
import { decryptRoute } from '@/views/decrypt/route'
import { aecryptRoute } from '@/views/aescrypt/route'
import { esp32Route } from '@/views/esp32/route'
import { echartsListRoute } from '@/views/echartsList/route'
import { remarkRoute } from '@/views/remark/route'
import { renderListRoute } from '@/views/renderList/route'
import { gridContainerRoute } from '@/views/gridContainer/route'
import LoginIndex from '@/views/login/index.vue'
import LoginRegister from '@/views/login/register.vue'
import HomeIndex from '@/views/home/index.vue'
import HomeView from '@/views/HomeView.vue'
import { useUserStore } from '@/stores/user'
import { useMenuStore } from '@/stores/menu'

const router = createRouter({
  // history: createWebHistory(import.meta.env.BASE_URL),
  history: createWebHistory(),
  // history: createMemoryHistory(),
  routes: [
    {
      path: '/home',
      name: 'home',
      component: HomeView,
      children: [
        ...appListRoute,
        ...menuListRoute,
        ...roleRoute,
        ...polymerizationRoute,
        ...echartsMapRoute,
        ...chinaMapRoute,
        ...decryptRoute,
        ...echartsListRoute, //常用图表收集
        ...remarkRoute, //备忘录
        ...gridContainerRoute, //网格容器布局
        ...renderListRoute, //处理百万条渲染列表组件
        ...aecryptRoute, //医事通aes解密
        ...taskRoute, //任务管理
        ...esp32Route //ESP32设备管理
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: LoginIndex
    },
    {
      path: '/register',
      name: 'register',
      component: LoginRegister
    },
    {
      path: '/myhome',
      name: 'myhome',
      component: HomeIndex
    },
    {
      path: '/',
      redirect: '/login'
    }
  ]
})
router.beforeEach((to, _, next) => {
  const userStore = useUserStore()
  if (userStore?.userInfo?.token) {
    const menuStore = useMenuStore()
    if (!menuStore.menu) {
      menuStore.getMenuList()
    }
    if (to.path === '/login' || to.path === '/register') {
      next('/home')
      return
    }
    next()
  } else {
    if (to.path === '/login' || to.path === '/register') {
      next()
      return
    }
    next('/login')
  }
})
export default router
